<?php

declare(strict_types=1);

namespace App\Api\Service;

use App\Constants\SettingConfig as SettingConfigConstant;
use App\Setting\Model\SettingConfig;
use Hyperf\Cache\Annotation\Cacheable;

use function Hyperf\Collection\data_get;

class ConfigService
{
    /**
     * 列表
     * @return array
     */
    public function index(): array
    {
        $configs = self::all();
        return [
            'logo' => (string)data_get($configs, SettingConfigConstant::LOGO),
            'user_home_image' => (string)data_get($configs, SettingConfigConstant::USER_HOME_IMAGE),
            'pick_up_location' => ConfigService::pickUpLocation(),
            'about_us' => (string)data_get($configs, SettingConfigConstant::ABOUT_US),
            'servers_phone' => (string)data_get($configs, SettingConfigConstant::SERVERS_PHONE),
        ];
    }

    /**
     * 取车地点
     * @return array
     */
    public static function pickUpLocation(): array
    {
        return explode("\n", str_replace("\r", '', (string)self::get(SettingConfigConstant::PICK_UP_LOCATION)));
    }

    /**
     * 清洁费
     * @return int
     */
    public static function cleaningFee(): int
    {
        return (int)self::get(SettingConfigConstant::CLEANING_FEE);
    }

    /**
     * 订单基础保险费
     * @return int
     */

    public static function orderBaseInsureFee(): int
    {
        return (int)self::get(SettingConfigConstant::ORDERBASEINSURE_FEE);
    }
    /**
     * 服务费
     * @return int
     */
    public static function serviceFee(): int
    {
        return (int)self::get(SettingConfigConstant::SERVICE_FEE);
    }

    /**
     * 支付失效时间(分钟)
     * @return int
     */
    public static function payLapseDate(): int
    {
        return (int)self::get(SettingConfigConstant::PAY_LAPSE_DATE, 30);
    }

    /**
     * 获取所有数据
     * @return array
     */
    #[Cacheable(prefix: 'config', ttl: 0)]
    public static function all(): array
    {
        return SettingConfig::query()
            ->pluck('value', 'key')
            ->toArray();
    }

    /**
     * 获取单个配置
     * @param string $key
     * @param mixed $default
     * @return mixed
     */
    public static function get(string $key, mixed $default = null): mixed
    {
        $all = self::all();
        return data_get($all, $key, $default);
    }
}
